package com.example.demo.security.userdetails.impl;

import com.example.demo.entity.AdminPermission;
import com.example.demo.entity.AdminUser;
import com.example.demo.mapper.AdminUserMapper;
import com.example.demo.security.userdetails.ManagerUserDetails;
import com.example.demo.security.userdetails.AdminUserManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 叮当猫的百宝箱
 * @since 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ManagerUserDetailsServiceImpl implements AdminUserManager {

    private final AdminUserMapper adminUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) {
        ManagerUserDetails managerUserDetails = null;
        AdminUser adminUser = adminUserMapper.findByUsername(username);
        if (adminUser != null) {
            managerUserDetails = new ManagerUserDetails();
            BeanUtils.copyProperties(adminUser, managerUserDetails);

            // 获取这个用户拥有的权限列表
            List<AdminPermission> permissions = adminUserMapper.findPermissionsById(adminUser.getId());

            List<GrantedAuthority> authorities = new ArrayList<>();
            for (AdminPermission permission : permissions) {
                authorities.add(permission::getPermissionIdentifier);
            }
            managerUserDetails.setAuthorities(authorities);
        }
        return managerUserDetails;
    }
}
